<?php


namespace App\Http\Controllers\User;


use App\Http\Controllers\BaseController;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;

class LoginController extends BaseController
{
    /**
     * 登录 /login
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function login(Request $request){
        $params = $request->only(['email', 'password']);

        //判断必填参数是否为空
        if (empty($params['email']) || empty($params['password'])){
            return $this->returnJson(BaseController::REQUIRED_FIELD_EMPTY, 'data cannot be processed');
        }

        //查询用户是否存在
        $user_data = User::where([
            'email'     =>  $params['email'],
            'password'  =>  md5($params['password'])
        ])->first(['id', 'email', 'scope', 'is_admin']);

        //判断用户是否存在
        if (!$user_data){
            return $this->returnJson(BaseController::UNAUTHORIZED, 'user credentials are invalid');
        }

        $user_data['scope'] = $user_data['scope'] == 0 ? "course" : "training";

        //生成token
        $user_data['token'] = $this->makeToken($user_data['id'], $user_data['is_admin']);

        return $this->returnJson(BaseController::OK, 'success', $user_data);
    }

    /**
     * 生成token
     * @param $user_id  用户id
     * @param $is_admin 是否是管理员
     * @return string
     */
    private function makeToken($user_id, $is_admin){
        $token = md5(time() . $user_id);

        //将信息存入Cache中
        Cache::put($token, [
            'id'        => $user_id,
            'is_admin'  => $is_admin
        ], 60 * 60 * 3);

        return $token;
    }

    /**
     * 登出 /logout
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function logout(Request $request){
        $token = $request->get('token');
        Cache::pull($token);
        return $this->returnJson(BaseController::OK, 'success');
    }

    /**
     * 获取当前时间 /datetime
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getCurrentTime(){
        return $this->returnJson(BaseController::OK, [
            'datetime'  =>  date('Y-m-d H:i:s', time())
        ]);
    }
}
